package com.online.onlineshop.services.impl;

import com.online.onlineshop.entity.Address;
import com.online.onlineshop.mapper.AddressMapper;
import com.online.onlineshop.services.ForAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service


public class ForAddressServiceImpl implements ForAddressService {
    @Autowired
    AddressMapper addressMapper;

    @Override
    public Address getByAid(Integer aid, Integer uid) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("aid", aid);
        Address address = addressMapper.selectByMap(map).get(0);

        if (address == null) {
            throw new RuntimeException("收货地址找不到");
        }
        if (address.getUid() != uid) {
            throw new RuntimeException("非法获取收货地址");
        }
        return address;
    }

    @Override
    public void putNewAddress(Integer uid, String userName, Address address) {
        address.setUid(uid);
        address.setCreatedUser(userName);
        address.setCreatedTime(new Date());
        address.setModifiedTime(new Date());
        address.setModifiedUser(userName);

        int insert = addressMapper.insert(address);
        if (insert != 1) {
            throw new RuntimeException("增添用户地址失败");
        }
    }

    @Override
    public void deleteAddress(Integer aid, Integer uid) {
        HashMap<String, Object> hs = new HashMap<>();
        hs.put("aid", aid);
        List<Address> rs = addressMapper.selectByMap(hs);
        if (rs == null) {
            throw new RuntimeException("数据找不到");
        }

        if (!rs.get(0).getUid().equals(uid)) {
            throw new RuntimeException("用户不匹配，非法删除");
        }

        int i = addressMapper.deleteByMap(hs);
        if (i != 1) {
            throw new RuntimeException("删除数据产生异常");
        }
    }

    @Override
    public List<Address> getAddressByUid(Integer uid) {
        HashMap<String, Object> ready = new HashMap<>();
        ready.put("uid", uid);

        List<Address> uids = addressMapper.selectByMap(ready);
        return uids;
    }


}
